#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QStackedWidget>
#include <QFileDialog>
#include "Logger.h"
#include "logview.h"
#include "filecomparisondialog.h"
#include "settingsdialog.h"
#include <QApplication>
#include <QTreeView>
#include <QFileSystemModel>
#include <QVBoxLayout>
#include <QWidget>
#include <QDir>
#include <QMessageBox>
#include <QFileInfo>
#include <QFile>
#include <QSet>
#include <QTimer>
#include "FileBackupThread.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    ,logViewer(new LogViewer(this))
    ,settingsDialog(nullptr)
{
    ui->setupUi(this);
    this->windowTitle();
    this->setWindowTitle("文件同步备份程序");
    logger= new Logger("log.txt");

    // 连接按钮的点击信号到对应的槽函数
    connect(ui->Button1, &QPushButton::clicked, this, [this]() {
        ui->stackedWidget->setCurrentIndex(0); // 切换到第一个页面
    });

    connect(ui->Button2, &QPushButton::clicked, this, [this]() {
        ui->stackedWidget->setCurrentIndex(1); // 切换到第二个页面
    });

    connect(ui->logButton, &QPushButton::clicked, this, &MainWindow::showLogViewer);

    connect(ui->pushButton, &QPushButton::clicked, this, &MainWindow::openSettingsDialog);

    // 初始化定时器，但此时不启动它
    backupTimer = new QTimer(this);
    connect(backupTimer, &QTimer::timeout, this, &MainWindow::performAutoBackup);
}

MainWindow::~MainWindow()
{
    delete logger;
    delete ui;
}

void MainWindow::showLogViewer() {
    logViewer->show();
}

void MainWindow::openSettingsDialog()
{
    SettingsDialog dialog(this);
    if (dialog.exec() == QDialog::Accepted) {
        // 用户点击了确定按钮
        int interval = dialog.getBackupInterval();
        QString unit = dialog.getBackupUnit();
        QTextBrowser *textBrowser = ui->textBrowser;


        // 转换间隔到毫秒
        int intervalInMilliseconds = 0;
        if (unit == "秒") {
            intervalInMilliseconds = interval * 1000;
        } else if (unit == "分钟") {
            intervalInMilliseconds = interval * 60 * 1000;
        } else if (unit == "小时") {
            intervalInMilliseconds = interval * 60 * 60 * 1000;
        }

        if (backupTimer->isActive()) {
            // 如果定时器已经启动，先停止它，然后再设置新的间隔并重新启动
            backupTimer->stop();
        }
        backupTimer->setInterval(intervalInMilliseconds);
        //logger->log("定时器设置时间：" + intervalInMilliseconds + "毫秒"); // 记录描述性数据
        textBrowser->append("定时器设置时间：" + QString::number(intervalInMilliseconds) + "毫秒" );
    }
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------
//页面一
//dev_a
void MainWindow::on_fileseclet1_clicked()
{
    QString dirName = QFileDialog::getExistingDirectory(this, tr("选择文件夹"), "/home", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    if (!dirName.isEmpty()) {
        ui->label_11->setText(dirName); // 更新label_11的文本为选择的文件夹路径
    }
}

void MainWindow::on_fileselect_up_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("选择文件"), "/home", "");
    if (!fileName.isEmpty()) {
        ui->showfile->setText(fileName); // 更新showfile的文本为选择的文件名
        ui->label_4->setText("文件");
    }
}

void MainWindow::on_fileselect_up_2_clicked()
{
    QString dirName = QFileDialog::getExistingDirectory(this, tr("选择文件夹"), "/home", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    if (!dirName.isEmpty()) {
        ui->showfile->setText(dirName); // 更新showfile的文本为选择的文件名
        ui->label_4->setText("文件夹");
    }
}

void MainWindow::on_start_beifen_clicked()//开始备份按钮
{
    QString fileToBackup = ui->showfile->text();  // 获取showfile的文本内容
    QString backupDirectory = ui->label_11->text(); // 获取label_11的文本内容
    QString type = ui->label_4->text();
    on_progressBar_valueChanged(0);

    QCheckBox *checkBox = ui ->checkBox;
    QCheckBox *checkBox_2 = ui ->checkBox_2;
    bool isauto=0;//no
    bool iszl=0;

    Qt::CheckState autostate = checkBox->checkState();
    Qt::CheckState zlstate = checkBox_2->checkState();

    // 检查文件是否选择
    if (fileToBackup.isEmpty()) {
        QMessageBox::warning(this, "警告", "请选择文件进行备份！");
        return; // 退出函数
    }

    // 检查备份目录是否选择
    if (backupDirectory.isEmpty()) {
        QMessageBox::warning(this, "警告", "请选择备份文件夹！");
        return; // 退出函数
    }

    QTextBrowser *textBrowser = ui->textBrowser;
    logger->log("正在准备" + fileToBackup + "备份到" + backupDirectory + "下"); // 记录描述性数据
    textBrowser->append("正在准备" + fileToBackup + "备份到" + backupDirectory + "下...");

    if (autostate == Qt::Checked){
        backupTimer->start(); // 启动定时器
        isauto=1;
        textBrowser->append("启动定时器");
    }else if (autostate == Qt::Unchecked) {
        isauto=0;
    }

    if (zlstate == Qt::Checked){
        iszl=1;
    }else if (zlstate == Qt::Unchecked) {
        iszl=0;
    }

    if (type == "文件") {
        performBackup1();
    } else {
        performBackup(iszl); // 进行备份
    }
}

void MainWindow::performBackup1() // 手动备份文件
{
    QTextBrowser *textBrowser = ui->textBrowser;
    QString backupFolder = ui->label_11->text();
    QString filename = ui->showfile->text();

    // 生成源文件路径和目标文件路径
    QString srcFilePath = filename; // filename 是要备份的源文件路径
    QString destFilePath = QDir(backupFolder).filePath(QFileInfo(filename).fileName()); // 目标路径

    // 检查目标文件是否存在
    if (QFile::exists(destFilePath)) {
        // 弹出比较窗口
        FileComparisonDialog dialog(srcFilePath, destFilePath,this);
        if (dialog.exec() == QDialog::Accepted) {
            if (!QFile::remove(destFilePath) || !QFile::copy(srcFilePath, destFilePath)) {
                textBrowser->append("错误: 无法备份文件 " + srcFilePath);
                logger->log("错误: 无法备份文件 " + srcFilePath); // 记录描述性数据
            } else {
                textBrowser->append("成功替换文件 " + destFilePath);
                logger->log("成功替换文件 " + destFilePath); // 记录描述性数据
            }
        } else {
            textBrowser->append("跳过文件 " + srcFilePath);
            logger->log("跳过文件 " + srcFilePath); // 记录描述性数据
        }
    } else {
        // 直接复制文件
        if (!QFile::copy(srcFilePath, destFilePath)) {
            textBrowser->append("错误: 无法备份文件 " + srcFilePath);
            logger->log("错误: 无法备份文件 " + srcFilePath); // 记录描述性数据
        } else {
            textBrowser->append("成功备份文件 " + destFilePath);
            logger->log("成功备份文件 " + destFilePath); // 记录描述性数据
        }
    }

    on_progressBar_valueChanged(100);
    textBrowser->append("\n备份成功: " + QFileInfo(filename).fileName() + " >>> " + backupFolder + "\n\n");
    logger->log("\n备份成功: " + QFileInfo(filename).fileName() + " >>> " + backupFolder + "\n"); // 记录描述性数据
}

void MainWindow::performBackup(bool& iszl) {
    QTextBrowser *textBrowser = ui->textBrowser;
    QString backupFolder = ui->label_11->text();
    QString sourceFolder = ui->showfile->text();

    // 创建备份文件夹
    QDir backupDir(backupFolder);
    if (!backupDir.exists() && !backupDir.mkpath(backupFolder)) {
        textBrowser->append("错误:无法创建备份文件夹！");
        return;
    }

    // 计算总文件数量
    int totalFiles = 0;
    std::function<void(const QString&)> countFiles = [&](const QString &dirPath) {
        QDir dir(dirPath);
        QStringList files = dir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot, QDir::DirsFirst | QDir::Name);
        for (const QString &entry : files) {
            /*QDir entryDir(dir.absoluteFilePath(entry));
            if (entryDir.isDir()) {
                countFiles(entryDir.absolutePath());
            } else {
                ++totalFiles;
            }*/
            QString fullPath = dir.absoluteFilePath(entry);
            QFileInfo fileInfo(fullPath);
            if (fileInfo.isDir()) {
                // 如果是目录，则递归调用
                countFiles(fullPath);
            } else {
                // 如果是文件，则增加计数器
                ++totalFiles;
            }
        }
    };
    countFiles(sourceFolder);

    copiedFiles = 0;

    // 复制文件和目录的递归函数
    std::function<void(const QString&, const QString&)> copyDirectory = [&](const QString &sourceDirPath, const QString &destDirPath) {
        QDir sourceDir(sourceDirPath);
        QStringList entries = sourceDir.entryList(QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot, QDir::DirsFirst | QDir::Name);

        for (const QString &entry : entries) {
            QString srcEntryPath = sourceDir.absoluteFilePath(entry);
            QString destEntryPath = destDirPath + "/" + entry;

            QFileInfo fileInfo(srcEntryPath);
            if (fileInfo.isDir()) {
                // 如果是目录，则创建目标目录并递归调用
                if (!QDir().mkpath(destEntryPath)) {
                    textBrowser->append("错误:无法创建子目录 " + destEntryPath);
                    logger->log("错误:无法创建子目录 " + destEntryPath);
                    continue; // 或返回错误代码，以停止递归
                }
                copyDirectory(srcEntryPath, destEntryPath);
            } else {
                // 如果是文件，则进行大小比较和复制逻辑
                QFileInfo destFileInfo(destEntryPath);
                bool fileExists = destFileInfo.exists();
                qint64 sourceFileSize = fileInfo.size();
                qint64 destFileSize = (fileExists) ? destFileInfo.size() : -1;

                if (QFile::exists(destEntryPath)) {
                    if(iszl == 1){
                        if (sourceFileSize != destFileSize) {
                            if (QFile::remove(destEntryPath)) { // 尝试删除目标文件
                                // 删除成功后，进行文件复制
                                if (sourceFileSize > 500 * 1024 * 1024) { // 文件大小超过500MB
                                    backupLargeFile(srcEntryPath, destEntryPath, iszl, totalFiles);
                                } else if (QFile::copy(srcEntryPath, destEntryPath)) {
                                    textBrowser->append("增量备份: 备份文件 " + srcEntryPath + " 到 " + destEntryPath);
                                    logger->log("增量备份: 备份文件 " + srcEntryPath + " 到 " + destEntryPath);
                                } else {
                                    textBrowser->append("错误:无法备份文件 " + srcEntryPath + " 到 " + destEntryPath);
                                    logger->log("错误:无法备份文件 " + srcEntryPath + " 到 " + destEntryPath);
                                }
                            } else {
                                textBrowser->append("错误:无法删除旧文件 " + destEntryPath);
                                logger->log("错误:无法删除旧文件 " + destEntryPath);
                            }
                        }
                        continue;
                    }

                    FileComparisonDialog dialog(srcEntryPath, destEntryPath, this);
                    if (dialog.exec() == QDialog::Accepted) {
                        QFile::remove(destEntryPath);
                        if (!QFile::copy(srcEntryPath, destEntryPath)) {
                            textBrowser->append("错误:无法备份文件 " + srcEntryPath);
                            logger->log("错误:无法备份文件 " + srcEntryPath);
                        } else {
                            textBrowser->append("成功替换文件 " + destEntryPath);
                            logger->log("成功替换文件 " + destEntryPath);
                        }
                    } else {
                        textBrowser->append("跳过文件 " + srcEntryPath);
                        logger->log("跳过文件 " + srcEntryPath);
                    }
                } else {
                    if (!QFile::copy(srcEntryPath, destEntryPath)) {
                        textBrowser->append("错误:无法备份文件 " + srcEntryPath);
                        logger->log("错误:无法备份文件 " + srcEntryPath);
                    } else {
                        if (sourceFileSize > 500 * 1024 * 1024) { // 文件大小超过500MB
                            backupLargeFile(srcEntryPath, destEntryPath, iszl, totalFiles);
                        }else if(iszl == 1){
                            textBrowser->append("增量备份:成功备份文件 " + destEntryPath);
                            logger->log("增量备份:成功备份文件 " + destEntryPath);
                        }else{
                            textBrowser->append("成功备份文件 " + destEntryPath);
                            logger->log("成功备份文件 " + destEntryPath);
                        }
                    }
                }
                copiedFiles++;
                if (totalFiles > 0) { // 避免除以零
                    on_progressBar_valueChanged((copiedFiles * 100) / totalFiles);
                }
            }
        }

    };


    copyDirectory(sourceFolder, backupFolder);

    on_progressBar_valueChanged(100);
    textBrowser->append("\n备份成功: " + sourceFolder + " >>> " + backupFolder + "\n\n");
    logger->log("\n备份成功: " + sourceFolder + " >>> " + backupFolder + "\n");
}

// 新增的 backupLargeFile 函数
void MainWindow::backupLargeFile(const QString& sourcePath, const QString& destPath, bool iszl,int totalFiles) {
    FileBackupThread* thread = new FileBackupThread(sourcePath, destPath, this);

    QTextBrowser *textBrowser = ui->textBrowser;
    connect(thread, &FileBackupThread::backupSuccess, this, [=](const QString& source, const QString& dest) {
        if (iszl == 1) {
            textBrowser->append("增量备份: 多线程成功备份文件 " + dest);
            // logger->log(...); // 注意：这里需要确保 logger 已经被定义和初始化
        } else {
            textBrowser->append("多线程成功备份文件 " + dest);
            // logger->log(...); // 注意：这里需要确保 logger 已经被定义和初始化
        }
        copiedFiles++;
        if (totalFiles > 0) { // 避免除以零
            on_progressBar_valueChanged((copiedFiles * 100) / totalFiles);
        }
        thread->deleteLater(); // 任务完成后删除线程对象
    });

    connect(thread, &FileBackupThread::backupFailed, this, [=](const QString& source, const QString& dest) {
        textBrowser->append("错误:多线程无法备份文件 " + source + " 到 " + dest);
        // logger->log(...); // 注意：这里需要确保 logger 已经被定义和初始化
        thread->deleteLater(); // 任务完成后删除线程对象
    });
    thread->start();
}


void MainWindow::on_progressBar_valueChanged(int value)
{
    ui->progressBar->setValue(value);
}

void MainWindow::on_checkBox_stateChanged(int arg1)
{
    QTextBrowser *textBrowser = ui->textBrowser;
    if (arg1 == Qt::Checked) {
        textBrowser->append("自动备份已启用");
    }else if (arg1 == Qt::Unchecked) {
        backupTimer->stop(); // 停止定时器
        textBrowser->append("停止定时器,自动备份已关闭");
    }
}

void MainWindow::on_checkBox_2_stateChanged(int arg1)
{
    QTextBrowser *textBrowser = ui->textBrowser;
    if (arg1 == Qt::Checked) {
        textBrowser->append("增量备份已启用");
    } else if (arg1 == Qt::Unchecked) {
        textBrowser->append("增量备份已关闭");
    }
}

void MainWindow::performAutoBackup() { //temp
    QString fileToBackup = ui->showfile->text();  // 获取要备份的文件路径
    QString backupDirectory = ui->label_11->text(); // 获取备份目录路径
    QString type = ui->label_4->text(); // 获取备份类型

    // 检查文件是否选择
    if (fileToBackup.isEmpty()) {
        QMessageBox::warning(this, "警告", "请选择文件进行备份！");
        return; // 退出函数
    }

    // 检查备份目录是否选择
    if (backupDirectory.isEmpty()) {
        QMessageBox::warning(this, "警告", "请选择备份文件夹！");
        return; // 退出函数
    }

    bool iszl =1;
    QTextBrowser *textBrowser = ui->textBrowser;
    textBrowser->append("自动备份:正在准备" + fileToBackup + "备份到" + backupDirectory + "下...");


    // 根据类型执行不同的备份操作
    if (type == "文件") {
        performBackup1();
    } else {
        performBackup(iszl); // 假设这个函数处理文件夹备份
    }
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------
//页面二
void MainWindow::on_toolButton_2_clicked()
{
    QString dirName = QFileDialog::getExistingDirectory(this, tr("选择文件夹"), "/home", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    QFileSystemModel *model = new QFileSystemModel();

    if (!dirName.isEmpty()) {
        ui->label_8->setText(dirName); // 更新label_8的文本为选择的文件夹路径
        model->setRootPath(dirName);
        ui->treeView1->setModel(model);
        ui->treeView1->setRootIndex(model->index(dirName)); // 设置视图的根索引为系统根路径
    }
}

void MainWindow::on_toolButton_3_clicked()
{

    QString dirName = QFileDialog::getExistingDirectory(this, tr("选择文件夹"), "/home", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
    QFileSystemModel *model = new QFileSystemModel();

    if (!dirName.isEmpty()) {
        ui->label_10->setText(dirName); // 更新label_8的文本为选择的文件夹路径
        model->setRootPath(dirName);
        ui->treeView2->setModel(model);
        ui->treeView2->setRootIndex(model->index(dirName)); // 设置视图的根索引为系统根路径
    }
}
//dev_B from B
void MainWindow::on_pushButton_5_clicked()//开始同步按钮
{
    QTextBrowser *textBrowser = ui->textBrowser_3;

    QString srcDir = ui->label_8->text(); // 第一选择的文件夹路径
    QString destDir = ui->label_10->text(); // 第二选择的文件夹路径
    QString srcDir1 = ui->label_8->text(); // 第一选择的文件夹路径
    QString destDir1 = ui->label_10->text(); // 第二选择的文件夹路径

    // 开始同步
    if (!srcDir.isEmpty() && !destDir.isEmpty()) {
        textBrowser->append("准备同步:"+srcDir+"<<<>>>"+destDir);

        ui->progressBar_2->setValue(0); // 重置进度条

        // 计算总进度条步骤
        int totalSteps = countFilesRecursively(srcDir1)+countFilesRecursively(destDir1);
        currentProgress = 0;

        QSet<QString> processedFiles;
        synchronizeDirectories(srcDir, destDir, totalSteps,processedFiles);
        // 可以添加完成后的提示
        textBrowser->append("同步完成");
    }

    on_progressBar_2_valueChanged(100);
}

int MainWindow::countFilesRecursively(const QDir& dir) {//遍历文件
    int fileCount = 0;
    QFileInfoList fileList = dir.entryInfoList(QDir::Files | QDir::NoDotAndDotDot);
    fileCount += fileList.size();

    QStringList dirList = dir.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
    for (const QString& subdir : dirList) {
        QDir subDir(dir.absoluteFilePath(subdir));
        fileCount += countFilesRecursively(subDir);
    }

    return fileCount;
}

void MainWindow::synchronizeDirectories(const QString &srcDir, const QString &destDir, int totalSteps,QSet<QString> &processedFiles) {
    QTextBrowser *textBrowser = ui->textBrowser_3;
    QProgressBar *progressBar = ui->progressBar_2;
    QDir source(srcDir);
    QDir destination(destDir);

    if (!source.exists() || !destination.exists()) {
        textBrowser->append("源或目标目录不存在");
        return;
    }

    // 获取源目录和目标目录中的文件和子目录
    QStringList sourceFiles = source.entryList(QDir::Files);
    QStringList sourceDirs = source.entryList(QDir::Dirs | QDir::NoDotAndDotDot);
    QStringList destFiles = destination.entryList(QDir::Files);
    QStringList destDirs = destination.entryList(QDir::Dirs | QDir::NoDotAndDotDot);

    // 复制文件从源到目标
    for (const QString &file : sourceFiles) {
        QString srcFilePath = source.absoluteFilePath(file);
        QString destFilePath = destination.absoluteFilePath(file);

        if (QFile::exists(destFilePath)) {
            if (processedFiles.contains(destFilePath)) {
                // 文件已处理，跳过
                continue;
            }
            // 处理文件冲突
            QMessageBox messageBox(this);
            messageBox.setText("文件冲突: " + file);
            messageBox.setInformativeText("目标文件已存在。请选择要保留的文件:");
            messageBox.addButton("保留源文件", QMessageBox::AcceptRole);
            messageBox.addButton("保留目标文件", QMessageBox::RejectRole);
            QPushButton *cancelButton = messageBox.addButton("中断此次同步", QMessageBox::ButtonRole::ActionRole);
            QPushButton *deleteButton = messageBox.addButton("删除目标文件", QMessageBox::DestructiveRole);
            messageBox.setWindowModality(Qt::ApplicationModal);
            messageBox.exec();

            if (messageBox.clickedButton() == cancelButton) {
                return;
            } else if (messageBox.clickedButton() == deleteButton) {
                QFile::remove(destFilePath);
                textBrowser->append("同步文件：删除" + destFilePath);
            } else {
                QFile srcFile(srcFilePath);
                QFile destFile(destFilePath);
                if (!QFile::copy(srcFilePath, destFilePath) ||
                    (srcFile.open(QIODevice::ReadOnly) && destFile.open(QIODevice::ReadOnly) && srcFile.readAll() != destFile.readAll())) {
                    QFile::copy(srcFilePath, destFilePath);
                    textBrowser->append("文件内容不同，已替换目标文件: " + destFilePath);
                }
            }
            processedFiles.insert(destFilePath); // 标记文件为已处理
        } else {
            QFile::copy(source.absoluteFilePath(file), destFilePath);
            textBrowser->append("同步文件：复制" + destFilePath);
            processedFiles.insert(destFilePath);  // 标记文件为已处理
        }
        currentProgress++;
        //textBrowser->append("----------调试信息0 复制文件从源到目标 " + QString::number(currentProgress)+"/"+QString::number(totalSteps));
        progressBar->setValue((currentProgress*100)/ totalSteps);
    }

    // 递归复制目录
    for (const QString &dir : sourceDirs) {
        QString srcSubDirPath = source.absoluteFilePath(dir);
        QString destSubDirPath = destination.absoluteFilePath(dir);

        if (!QDir(destSubDirPath).exists()) {
            QDir().mkpath(destSubDirPath);
        }
        synchronizeDirectories(srcSubDirPath, destSubDirPath,totalSteps,processedFiles);
        progressBar->setValue((currentProgress*100)/ totalSteps);
    }

    // 递归处理目标目录的子目录
    for (const QString &dir : destDirs) {
        QString destSubDirPath = destination.absoluteFilePath(dir);
        QString srcSubDirPath = source.absoluteFilePath(dir);

        if (!QDir(srcSubDirPath).exists()) {
            // 处理目录冲突
            QMessageBox messageBox(this);
            messageBox.setText("目录冲突: " + dir);
            messageBox.setInformativeText("源目录不存在，目标目录存在。请选择要保留的目录:");
            QPushButton *createButton = messageBox.addButton("保留目标目录", QMessageBox::AcceptRole);
            QPushButton *deleteButton = messageBox.addButton("删除目标目录", QMessageBox::RejectRole);
            QPushButton *cancelButton = messageBox.addButton("取消", QMessageBox::ButtonRole::ActionRole);
            messageBox.setWindowModality(Qt::ApplicationModal);
            messageBox.exec();

            if (messageBox.clickedButton() == cancelButton) {
                return;
            }else if (messageBox.clickedButton() == deleteButton) {
                QDir(destSubDirPath).removeRecursively();
                textBrowser->append("同步目录：删除" + destSubDirPath);
            }else if(messageBox.clickedButton() == createButton){
                if (QDir(srcSubDirPath).mkpath(".")) { // 尝试创建源目录
                    textBrowser->append("同步目录：在源中创建 " + srcSubDirPath);
                }
            }
        } else {
            synchronizeDirectories(srcSubDirPath, destSubDirPath, totalSteps, processedFiles);
        }
        //textBrowser->append("----------调试信息1 递归处理目标目录的子目录 " + QString::number(currentProgress)+"/"+QString::number(totalSteps));
        progressBar->setValue((currentProgress*100)/ totalSteps);
    }

    // 从目标到源目录同步
    for (const QString &file : destFiles) {
        QString destFilePath = destination.absoluteFilePath(file);
        QString srcFilePath = source.absoluteFilePath(file);

        if (!QFile::exists(srcFilePath)) {
            // 处理文件冲突
            QMessageBox messageBox(this);
            messageBox.setText("文件冲突: " + file);
            messageBox.setInformativeText("源文件不存在，目标文件存在。请选择要保留的文件:");
            messageBox.addButton("保留目标文件", QMessageBox::AcceptRole);
            QPushButton *deleteButton = messageBox.addButton("删除目标文件", QMessageBox::RejectRole);
            QPushButton *cancelButton = messageBox.addButton("取消", QMessageBox::ButtonRole::ActionRole);
            messageBox.setWindowModality(Qt::ApplicationModal);
            messageBox.exec();

            if (messageBox.clickedButton() == cancelButton) {
                return;
            } else if (messageBox.clickedButton() == deleteButton) {
                QFile::remove(destFilePath);
                textBrowser->append("同步文件：删除" + destFilePath);
            }else{
                QFile::copy(destFilePath, srcFilePath);
                textBrowser->append("同步文件：从目标覆盖源 " + srcFilePath);
            }
        }
        //textBrowser->append("----------调试信息2 从目标到源目录同步 " + QString::number(currentProgress)+"/"+QString::number(totalSteps));
        progressBar->setValue((currentProgress*100)/ totalSteps);
    }
}

void MainWindow::on_progressBar_2_valueChanged(int value){
    ui->progressBar_2->setValue(value);
}
